//
//  ProblemOffer17.swift
//  TestProject
//
//  Created by 武侠 on 2021/7/5.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit

/*
 剑指 Offer 17. 打印从1到最大的n位数 ✅
 输入数字 n，按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3，则打印出 1、2、3 一直到最大的 3 位数 999。

 示例 1:
     输入: n = 1
     输出: [1,2,3,4,5,6,7,8,9]
 说明：
     用返回一个整数列表来代替打印
     n 为正整数
 */
@objcMembers class ProblemOffer17: NSObject {
    func solution() {
//        print(removeFirstZero())
        print(printNumbersLarge(3))
    }
    
    // 在Int范围内
    func printNumbers(_ n: Int) -> [Int] {
        var end = 1
        for _ in 0..<n {
            end *= 10
        }
        
        var list = Array(repeating: 1, count: end-1)
        for i in 1..<end {
            list[i-1] = i
        }
        
        return list;
    }
    
    // 超过Int范围
    var nList: [String] = []
    var loop: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    var chartList: [Character] = []
    var n = 0
    func printNumbersLarge(_ n: Int) -> [String] {
        self.n = n
        self.chartList = Array(repeating: "0", count: n)
        
        deep(n)
        return self.nList
    }

    
    /// x: 当前的深度
    func deep(_ x: Int)  {
        if x == 0 {
            if let s = removeFirstZero() {
                self.nList.append(s)
            }
            return
        }
        
        for c in loop {
            self.chartList[self.n-x] = c
            deep(x-1)
        }
        
    }
    func removeFirstZero() -> String? {
        var start = 0
        for (i, c) in self.chartList.enumerated() {
            if c == "0" {
                start = i+1
            } else {
                break
            }
        }
        
        return start == self.chartList.count ? nil : String(self.chartList[start..<self.chartList.count])
    }
}
